package com.yx.cloud.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.iot.common.utils.LogUtils;
import com.yx.cloud.Interface.BounceCallBack;
import com.yx.cloud.MyApplication;
import com.yx.cloud.R;
import com.yx.cloud.activity.MusicAlbumDetailActivity;
import com.yx.cloud.activity.MusicPlayingActivity;
import com.yx.cloud.adapter.MusicAlbumListAdapter;
import com.yx.cloud.header.NormalBounceHandler;
import com.yx.cloud.product.sdk.tmall.AliGenieSdk;
import com.yx.cloud.product.sdk.tmall.MusicInfo;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.view.BounceLayout;
import com.yx.cloud.view.DefaultFooter;
import com.yx.cloud.view.DefaultHeader;
import com.yx.cloud.view.MusicBottomSheetDialog;
import com.yx.cloud.product.sdk.tmall.req.CreateMusicListParam;
import com.yx.cloud.product.sdk.tmall.req.GetMusicListCateContentParam;
import com.yx.cloud.product.sdk.tmall.req.GetMusicListParam;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import com.iot.common.utils.Event;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class MusicAlbumListFragment extends Fragment implements MusicAlbumListAdapter.InnerItemOnclickListener, MusicBottomSheetDialog.MusicListOperation {
    private RecyclerView mListView;
    private MusicAlbumListAdapter musicListAdapter;
    private List<MusicInfo> mMusicList;
    private boolean mIsRefresh;
    private BounceLayout blMusic;
    private FrameLayout fl_message_container;
    private String topicType = "";
    private Long cateId;
    private String contentType;
    private LinearLayout llNoMusic;
    private long totalSize = 0;


    public MusicAlbumListFragment(long cateId, String contentType) {
        this.cateId = cateId;
        this.contentType = contentType;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.music_list_fragment, container, false);
        initView(view);
        EventBus.getDefault().register(this);
        getMusicListCateContent();
        return view;
    }

    public void getMusicListCateContent(){
        if(totalSize == 0){
            new Thread(() -> {
                getMusicListCateContent(1,20,true);
            }).start();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_GET_MUSIC_LIST:
                if(event.isResult()){
                    Log.d("music","receive music list");
                    GetMusicListCateContentParam param = (GetMusicListCateContentParam) event.getExtra();
                    if(cateId == param.getCateId()){
                        totalSize = param.getTotalSize();
                        onDataUpdate(event);
                        Log.d("music","update music list");
                    }
                }else {
                    String message = (String)event.getContent();
                    Log.d("music","return result is not 200，message is " + message);
                    ToastUtil.show(getActivity(), message, Toast.LENGTH_SHORT);
                    if (mIsRefresh) {
                        blMusic.setRefreshCompleted();
                    } else {
                        blMusic.setLoadingMoreCompleted();
                    }
                }
                break;
            case Event.MESSAGE_TYPE_CREATE_MUSIC_LIST:
                if(event.isResult()){
                    if(cateId == 10000L){
                        Intent intent = new Intent(getActivity(), MusicPlayingActivity.class);
                        intent.putExtra("musicInfo", new Gson().toJson(musicListAdapter.getmMusicInfoList().get(musicListAdapter.getSelectedItem())));
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.enteralpha,
                                R.anim.default_anim);
                    }
                }else {
                    ToastUtil.show(getActivity(), event.getContent().toString(), Toast.LENGTH_SHORT);
                }
                break;
            case Event.MESSAGE_TYPE_MUSIC_PLAY_SWITCH:
                Log.d("music","set music playing");
                int id = (int)event.getContent();
                musicListAdapter.selectItem(id);
                break;
        }
    }

    private void initView(View view) {
        llNoMusic = view.findViewById(R.id.ll_noMusic);
        //设置线性布局管理器类型
        mListView = view.findViewById(R.id.music_ListView);
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 3,GridLayoutManager.VERTICAL, false);
        mListView.setLayoutManager(layoutManager);
        mMusicList = new ArrayList<>();
        musicListAdapter = new MusicAlbumListAdapter(getContext(), mMusicList,cateId);
        musicListAdapter.setOnInnerItemOnClickListener(this);
        mListView.setAdapter(musicListAdapter);


        blMusic = view.findViewById(R.id.bl_music_list);

        blMusic.setBounceHandler(new NormalBounceHandler(), mListView);//设置滚动冲突的控制类
        //自定义事件分发处理
        blMusic.setEventForwardingHelper((downX, downY, moveX, moveY) -> true);

        fl_message_container = view.findViewById(R.id.fl_music_list_fragment);
        blMusic.setHeaderView(new DefaultHeader(getContext()), fl_message_container);//设置刷新头，null意味着没有刷新头，不调用该函数意为着空
        blMusic.setFooterView(new DefaultFooter(getContext()), fl_message_container);
        blMusic.setBounceCallBack(new BounceCallBack() {
            @Override
            public void startRefresh() {
                Log.d("music","startRefresh");
                new Thread(() -> {
                    getMusicListCateContent(1,20,true);
                }).start();
            }

            @Override
            public void startLoadingMore() {
                Log.d("music","startLoadingMore");
                if(totalSize == musicListAdapter.getItemCount() && musicListAdapter.getItemCount() > 0){
                    GetMusicListCateContentParam param = new GetMusicListCateContentParam();
                    param.setCateId(cateId);
                    param.setTotalSize(totalSize);
                    mIsRefresh = false;
                    Event.newBuilder().type(Event.MESSAGE_TYPE_GET_MUSIC_LIST).result(true).extra(param).content(null).send();
                }else {
                    new Thread(() -> {
                        getMusicListCateContent(musicListAdapter.getItemCount() / 20 + 1, 20, false);
                    }).start();

                }
            }
        });

    }

    private void getMusicList(int offset, int limit, final boolean isRefresh){
        Log.d("music"," 消息: =======getMusicList======== :" + isRefresh + "topicType " + topicType);
        mIsRefresh = isRefresh;
        mMusicList = new ArrayList<>();
        GetMusicListParam param = new GetMusicListParam();
        param.setPageNum(offset);
        param.setPageSize(limit);
        param.setTopicType(topicType);
        //new Thread(() -> AliGenieSdk.get().getMusicListByTopicId(param)).start();
    }

    private void getMusicListCateContent(int pageNum, int pageSize, final boolean isRefresh){
        Log.d("music"," 消息: =======getMusicList======== :" + isRefresh + "topicType = " + topicType + "pageNum =" + pageNum + "pageSize = " + pageSize );
        mIsRefresh = isRefresh;
        mMusicList = new ArrayList<>();
        GetMusicListCateContentParam param = new GetMusicListCateContentParam();
        param.setPageNum(pageNum);
        param.setPageSize(pageSize);
        param.setAlbum(true);
        param.setCateId(cateId);
        if(cateId == 10000L){
            AliGenieSdk.get().getListRecommendContent(param);
        }else {
            AliGenieSdk.get().getMusicListCateContent(param);
        }

    }

    private void getListRecommendContent(int count,final boolean isRefresh){
        Log.d("music"," 消息: =======getMusicList======== :" + isRefresh + "topicType = " + topicType + "count" + count);
        mIsRefresh = isRefresh;
        mMusicList = new ArrayList<>();
        GetMusicListCateContentParam param = new GetMusicListCateContentParam();
        param.setPageSize(count);
        param.setCateId(cateId);
        AliGenieSdk.get().getListRecommendContent(param);
    }

    @Override
    public void itemClick(View v, int position) {
        Log.d("music","itemClick");
        if(cateId == 10000L) {
            new Thread(() -> {
                createPlayList(position);
            }).start();
        }else {
            new Thread(() -> {
                Intent intent = new Intent(getActivity(), MusicAlbumDetailActivity.class);
                intent.putExtra("musicInfo", new Gson().toJson(musicListAdapter.getItem(position)));
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.in_from_right,
                        R.anim.out_to_left);
            }).start();
        }
    }

    @Override
    public void createPlayList(int index) {
        CreateMusicListParam param = new CreateMusicListParam();
        param.setContentType(contentType);
        param.setPlayIndex(index);
        //列表循环：Repeat；随机：Shuffle；单曲循环：RepeatOne；顺序播放：Normal。
        param.setPlayMode("Normal");
        List<MusicInfo> createList = new ArrayList<>();
        if(cateId == 10000L){
            param.setContentType("content");
            createList.add(musicListAdapter.getmMusicInfoList().get(index));
            param.setPlayIndex(0);
        }else {
            createList.addAll(musicListAdapter.getmMusicInfoList());
        }
        AliGenieSdk.get().createMusicList(createList, param);
    }

    @Override
    public void play() {

    }

    @Override
    public void pause() {

    }

    @Override
    public void next() {

    }

    @Override
    public void previous() {

    }

    @Override
    public void updateData() {

    }

    @Override
    public List<MusicInfo> getMusicInfoList() {
        return null;
    }

    @Override
    public void onDataUpdate(Event event) {
        if (event.isResult()) {
            List<MusicInfo> result = (List<MusicInfo>) event.getContent();
            Log.d("music","parse music list");
            parseMusicInfo(result, mIsRefresh);
        } else {
            llNoMusic.setVisibility(View.VISIBLE);
        }
    }

    private void parseMusicInfo(List<MusicInfo> result, boolean isRefresh) {
        List<MusicInfo> tempList = result;
        LogUtils.i("getMusicInfoList contentType is--> : " +contentType);
        if (isRefresh) {
            musicListAdapter.updateMusic(tempList);
            blMusic.setRefreshCompleted();
        } else {
            //TODO 这里不确定会不会取到错误数据 有新消息或者消息被删了  下标有变化 比如 以前是取10-20  新来了一条消息后 继续取10-20 其实取到的是以前的9-19
            //可能需要做去重和重定位
            musicListAdapter.addMusic(tempList);
            blMusic.setLoadingMoreCompleted();
        }

        if (tempList == null || tempList.size() == 0) {
            if (musicListAdapter.getItemCount() == 0) {
                fl_message_container.setVisibility(View.GONE);
                llNoMusic.setVisibility(View.VISIBLE);
            } else {
                ToastUtil.showShort(MyApplication.get(), R.string.U_NoMoreRecords);
            }
        } else {
            fl_message_container.setVisibility(View.VISIBLE);
            LogUtils.i("getMessageList size--> : " + tempList.size());
            llNoMusic.setVisibility(View.GONE);
        }
    }
}
